package com.liliudong.cursormate.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liliudong.cursormate.common.R;
import com.liliudong.cursormate.common.constant.SecurityConst;
import com.liliudong.cursormate.common.exception.BusinessException;
import com.liliudong.cursormate.entity.SysUser;
import com.liliudong.cursormate.service.SysUserRoleService;
import com.liliudong.cursormate.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 系统用户控制器
 *
 * @author Liudong.li
 * @version 1.0
 * @project cursor-mate
 * @date 2023/10/23 23:08:27
 */
@RestController
@RequestMapping("/v1/sys-user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;

    /**
     * 登录
     *
     * @param sysUser
     * @return {@link R}<{@link SaTokenInfo}>
     */
    @PostMapping("/login")
    public R<SaTokenInfo> login(@RequestBody SysUser sysUser) {
        SaTokenInfo tokenInfo = sysUserService.login(sysUser);
        return R.success(tokenInfo);
    }


    /**
     * 退出登录
     *
     * @return {@link R}<{@link ?}>
     */
    @GetMapping("/logout")
    public R<?> logout() {
        StpUtil.logout();
        return R.success();
    }

    /**
     * 个人信息
     *
     * @return {@link R}<{@link ?}>
     */
    @GetMapping("/profile")
    public R<SysUser> profile() {
        SysUser sysUser = sysUserService.profile();
        return R.success(sysUser);
    }

    /**
     * 添加用户
     *
     * @param sysUser sys用户
     * @return {@link R}<{@link ?}>
     */
    @PostMapping
    @Transactional
    @SaCheckPermission("sys:user:add")
    public R<?> create(@RequestBody SysUser sysUser) {
        // 默认密码
        String bcryptPassword = DigestUtil.bcrypt(SecurityConst.DEFAULT_PASSWORD);
        sysUser.setPassword(bcryptPassword);
        // 添加用户
        sysUserService.save(sysUser);
        // 添加用户角色信息
        if (CollectionUtil.isNotEmpty(sysUser.getRoleCodeList())) {
            sysUserRoleService.saveBatchByUserId(sysUser.getId(), sysUser.getRoleCodeList());
        }
        return R.success();
    }

    /**
     * 根据ID删除
     *
     * @param id id
     * @return {@link R}<{@link ?}>
     */
    @DeleteMapping("/{id}")
    @Transactional
    @SaCheckPermission("sys:user:del")
    public R<?> del(@PathVariable Long id) {
        sysUserService.removeById(id);
        sysUserRoleService.removeByUserId(id);
        return R.success();
    }

    /**
     * 按id更新
     *
     * @param sysUser sys用户
     * @return {@link R}<{@link ?}>
     */
    @PutMapping
    @Transactional
    @SaCheckPermission("sys:user:edit")
    public R<?> updateById(@RequestBody SysUser sysUser) {
        sysUser.setPassword(null);
        sysUserService.updateById(sysUser);
        sysUserRoleService.removeByUserId(sysUser.getId());
        sysUserRoleService.saveBatchByUserId(sysUser.getId(), sysUser.getRoleCodeList());
        return R.success();
    }

    /**
     * 分页查询
     *
     * @param page     页
     * @param pageSize 页面大小
     * @return {@link R}<{@link Page}<{@link SysUser}>>
     */
    @GetMapping("/page")
    @SaCheckPermission("sys:user:page")
    public R<Page<SysUser>> page(@RequestParam(defaultValue = "1") Long page,
                                 @RequestParam(defaultValue = "10") Long pageSize) {
        Page<SysUser> sysUserPage = sysUserService.page(Page.of(page, pageSize));
        return R.success(sysUserPage);
    }

    /**
     * ID查询详情
     *
     * @param id id
     * @return {@link R}<{@link SysUser}>
     */
    @GetMapping("/{id}")
    @SaCheckPermission("sys:user:info")
    public R<SysUser> info(@PathVariable Long id) {
        SysUser sysUser = sysUserService.getById(id);
        if (Objects.isNull(sysUser)) {
            throw new BusinessException("用户不存在");
        }
        List<String> roleCodeList = sysUserRoleService.listRoleCodeListByUserId(id);
        sysUser.setRoleCodeList(roleCodeList);
        return R.success(sysUser);
    }
}
